package com.lwl.shua.class03;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lwl
 * @Description TODO
 * @date 2025/9/7 17:47
 */
public class Code01Lc03LengthOfLongestSubstring {
    @Test
    public void test() {
        System.out.println(lengthOfLongestSubstring("abba"));
    }

//    public int lengthOfLongestSubstring2(String s) {
//        // todo 使用动态规划实现一下
//    }

    public int lengthOfLongestSubstring(String s) {
        char[] charArray = s.toCharArray();
        int left = 0;
        int res = 0;
        Map<Character, Integer> charIndexMap = new HashMap<>();
        for (int right = 0; right < charArray.length; right++) {
            if (charIndexMap.containsKey(charArray[right]) && left <= charIndexMap.get(charArray[right])) {
                left = charIndexMap.get(charArray[right]) + 1;
            }
            charIndexMap.put(charArray[right], right);
            res = Math.max(res, right - left + 1);
        }
        return res;
    }
}
